// 会员发布管理 JavaScript
let currentPage = 1;
let currentFilters = {};
let selectedPublicationId = null;

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    // 检查管理员token
    const adminToken = localStorage.getItem('adminToken');
    if (!adminToken) {
        showAlert('请先登录管理员账户', 'error');
        setTimeout(() => {
            window.location.href = '/admin-portal';
        }, 2000);
        return;
    }
    
    loadStatistics();
    loadPublications();
    loadScaleOptions();
});

// 加载统计数据
function loadStatistics() {
    apiRequest('/api/admin/member-publications/stats', {
        method: 'GET',
        headers: {
            'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
        }
    })
    .then(response => {
        if (response.code === 200) {
            displayStatistics(response.data);
        }
    })
    .catch(error => {
        console.error('加载统计数据失败:', error);
    });
}

// 显示统计数据
function displayStatistics(stats) {
    document.getElementById('totalPublications').textContent = stats.total_publications || 0;
    document.getElementById('activePublications').textContent = stats.active_publications || 0;
    document.getElementById('totalViews').textContent = stats.total_access_count || 0;
    document.getElementById('totalAssessments').textContent = stats.total_assessment_count || 0;
    
    // 计算增长率和平均值
    const activeRate = stats.total_publications > 0 ? 
        Math.round((stats.active_publications / stats.total_publications) * 100) : 0;
    document.getElementById('activeRate').textContent = activeRate + '%';
    
    const avgViews = stats.total_publications > 0 ? 
        Math.round(stats.total_access_count / stats.total_publications) : 0;
    document.getElementById('avgViews').textContent = avgViews;
    
    const avgAssessments = stats.total_publications > 0 ? 
        Math.round(stats.total_assessment_count / stats.total_publications) : 0;
    document.getElementById('avgAssessments').textContent = avgAssessments;
    
    // 设置增长率（这里简化处理，实际应该从后端获取）
    document.getElementById('publicationGrowth').textContent = '+12%';
}

// 加载发布列表
function loadPublications(page = 1) {
    currentPage = page;
    
    // 构建查询参数
    const params = new URLSearchParams({
        page: page,
        per_page: 20,
        search: document.getElementById('searchInput')?.value || '',
        status: document.getElementById('statusFilter')?.value || '',
        scale_id: document.getElementById('scaleFilter')?.value || '',
        sort_by: document.getElementById('sortBy')?.value || 'created_at',
        sort_order: 'desc'
    });
    
    apiRequest(`/api/admin/member-publications?${params}`, {
        method: 'GET',
        headers: {
            'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
        }
    })
    .then(response => {
        if (response.code === 200) {
            displayPublications(response.data.publications);
            displayPagination(response.data.pagination);
            updatePublicationCount(response.data.pagination.total);
        }
    })
    .catch(error => {
        console.error('加载发布列表失败:', error);
        showAlert('加载发布列表失败', 'error');
    });
}

// 显示发布列表
function displayPublications(publications) {
    const tbody = document.getElementById('publicationsTableBody');
    
    if (!publications || publications.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="9" class="text-center py-5">
                    <i class="bi bi-inbox display-1 text-muted"></i>
                    <p class="mt-3 text-muted">暂无发布记录</p>
                </td>
            </tr>
        `;
        return;
    }
    
    tbody.innerHTML = publications.map(publication => `
        <tr>
            <td>
                <input type="checkbox" class="form-check-input publication-checkbox" value="${publication.id}">
            </td>
            <td>
                <div>
                    <h6 class="mb-1">${publication.scale.title}</h6>
                    <small class="text-muted">${publication.scale.description || ''}</small>
                    <div class="mt-1">
                        <span class="badge bg-light text-dark">${publication.scale.question_count} 题</span>
                        <span class="badge bg-light text-dark">版本 ${publication.scale.version}</span>
                    </div>
                </div>
            </td>
            <td>
                <div>
                    <strong>${publication.member.username || publication.member.email}</strong>
                    <br>
                    <small class="text-muted">${publication.member.email}</small>
                    <br>
                    <span class="badge bg-info">${publication.member.membership_type || 'basic'}</span>
                </div>
            </td>
            <td>
                <div>
                    ${publication.custom_title ? `<strong>${publication.custom_title}</strong><br>` : ''}
                    ${publication.custom_description ? `<small class="text-muted">${publication.custom_description}</small>` : '<span class="text-muted">无自定义信息</span>'}
                </div>
            </td>
            <td>
                <span class="badge ${publication.is_active ? 'bg-success' : 'bg-secondary'}">
                    ${publication.is_active ? '活跃' : '非活跃'}
                </span>
            </td>
            <td>
                <div>
                    <strong>${publication.access_count}</strong> 次访问
                    <br>
                    <small class="text-muted">
                        ${publication.last_accessed_at ? 
                            `最后访问: ${formatDate(publication.last_accessed_at)}` : 
                            '从未访问'
                        }
                    </small>
                </div>
            </td>
            <td>
                <div>
                    <strong>${publication.assessment_count}</strong> 次测评
                    <br>
                    <small class="text-muted">
                        转化率: ${publication.access_count > 0 ? 
                            Math.round((publication.assessment_count / publication.access_count) * 100) : 0
                        }%
                    </small>
                </div>
            </td>
            <td>
                <small>${formatDate(publication.created_at)}</small>
            </td>
            <td>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary" onclick="viewPublicationDetail(${publication.id})" title="查看详情">
                        <i class="bi bi-eye"></i>
                    </button>
                    <button class="btn btn-outline-warning" onclick="managePublicationStatus(${publication.id}, '${publication.scale.title}', ${publication.is_active})" title="状态管理">
                        <i class="bi bi-gear"></i>
                    </button>
                    <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">
                            <i class="bi bi-three-dots"></i>
                        </button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="#" onclick="copyPublicationLink(${publication.id})">
                                <i class="bi bi-link me-2"></i>复制链接
                            </a></li>
                            <li><a class="dropdown-item" href="#" onclick="viewPublicationAssessments(${publication.id})">
                                <i class="bi bi-file-text me-2"></i>查看测评
                            </a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item text-danger" href="#" onclick="deletePublication(${publication.id}, '${publication.scale.title}')">
                                <i class="bi bi-trash me-2"></i>删除发布
                            </a></li>
                        </ul>
                    </div>
                </div>
            </td>
        </tr>
    `).join('');
}

// 显示分页
function displayPagination(pagination) {
    const paginationElement = document.getElementById('pagination');
    
    if (pagination.pages <= 1) {
        paginationElement.innerHTML = '';
        return;
    }
    
    let paginationHTML = '';
    
    // 上一页
    if (pagination.has_prev) {
        paginationHTML += `
            <li class="page-item">
                <a class="page-link" href="#" onclick="loadPublications(${pagination.page - 1})">上一页</a>
            </li>
        `;
    }
    
    // 页码
    for (let i = Math.max(1, pagination.page - 2); i <= Math.min(pagination.pages, pagination.page + 2); i++) {
        paginationHTML += `
            <li class="page-item ${i === pagination.page ? 'active' : ''}">
                <a class="page-link" href="#" onclick="loadPublications(${i})">${i}</a>
            </li>
        `;
    }
    
    // 下一页
    if (pagination.has_next) {
        paginationHTML += `
            <li class="page-item">
                <a class="page-link" href="#" onclick="loadPublications(${pagination.page + 1})">下一页</a>
            </li>
        `;
    }
    
    paginationElement.innerHTML = paginationHTML;
}

// 更新发布数量
function updatePublicationCount(total) {
    document.getElementById('publicationCount').textContent = `共 ${total} 个发布`;
}

// 搜索发布
function searchPublications() {
    loadPublications(1);
}

// 加载量表选项
function loadScaleOptions() {
    apiRequest('/api/admin/scales?publisher_type=system', {
        method: 'GET',
        headers: {
            'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
        }
    })
    .then(response => {
        if (response.code === 200) {
            const scaleFilter = document.getElementById('scaleFilter');
            const scales = response.data.scales;
            
            scales.forEach(scale => {
                const option = document.createElement('option');
                option.value = scale.id;
                option.textContent = scale.title;
                scaleFilter.appendChild(option);
            });
        }
    })
    .catch(error => {
        console.error('加载量表选项失败:', error);
    });
}

// 查看发布详情
function viewPublicationDetail(publicationId) {
    apiRequest(`/api/admin/member-publications/${publicationId}`, {
        method: 'GET',
        headers: {
            'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
        }
    })
    .then(response => {
        if (response.code === 200) {
            displayPublicationDetail(response.data);
            const modal = new bootstrap.Modal(document.getElementById('publicationDetailModal'));
            modal.show();
        }
    })
    .catch(error => {
        console.error('获取发布详情失败:', error);
        showAlert('获取发布详情失败', 'error');
    });
}

// 显示发布详情
function displayPublicationDetail(publication) {
    const content = document.getElementById('publicationDetailContent');
    content.innerHTML = `
        <div class="row">
            <div class="col-md-6">
                <h6>量表信息</h6>
                <table class="table table-sm table-borderless">
                    <tr><td><strong>量表名称:</strong></td><td>${publication.scale.title}</td></tr>
                    <tr><td><strong>量表描述:</strong></td><td>${publication.scale.description || '-'}</td></tr>
                    <tr><td><strong>题目数量:</strong></td><td>${publication.scale.question_count} 题</td></tr>
                    <tr><td><strong>预估时间:</strong></td><td>${publication.scale.estimated_time || '-'} 分钟</td></tr>
                    <tr><td><strong>量表版本:</strong></td><td>${publication.scale.version}</td></tr>
                </table>
            </div>
            <div class="col-md-6">
                <h6>发布信息</h6>
                <table class="table table-sm table-borderless">
                    <tr><td><strong>发布会员:</strong></td><td>${publication.member.username || publication.member.email}</td></tr>
                    <tr><td><strong>会员邮箱:</strong></td><td>${publication.member.email}</td></tr>
                    <tr><td><strong>会员类型:</strong></td><td><span class="badge bg-info">${publication.member.membership_type || 'basic'}</span></td></tr>
                    <tr><td><strong>发布状态:</strong></td><td><span class="badge ${publication.is_active ? 'bg-success' : 'bg-secondary'}">${publication.is_active ? '活跃' : '非活跃'}</span></td></tr>
                    <tr><td><strong>发布时间:</strong></td><td>${formatDate(publication.created_at)}</td></tr>
                </table>
            </div>
        </div>
        
        ${publication.custom_title || publication.custom_description ? `
        <div class="row mt-3">
            <div class="col-12">
                <h6>自定义信息</h6>
                <table class="table table-sm table-borderless">
                    ${publication.custom_title ? `<tr><td><strong>自定义标题:</strong></td><td>${publication.custom_title}</td></tr>` : ''}
                    ${publication.custom_description ? `<tr><td><strong>自定义描述:</strong></td><td>${publication.custom_description}</td></tr>` : ''}
                </table>
            </div>
        </div>
        ` : ''}
        
        <div class="row mt-3">
            <div class="col-md-6">
                <h6>访问统计</h6>
                <table class="table table-sm table-borderless">
                    <tr><td><strong>总访问次数:</strong></td><td>${publication.access_count}</td></tr>
                    <tr><td><strong>最后访问:</strong></td><td>${publication.last_accessed_at ? formatDate(publication.last_accessed_at) : '从未访问'}</td></tr>
                </table>
            </div>
            <div class="col-md-6">
                <h6>测评统计</h6>
                <table class="table table-sm table-borderless">
                    <tr><td><strong>总测评次数:</strong></td><td>${publication.assessment_count}</td></tr>
                    <tr><td><strong>转化率:</strong></td><td>${publication.access_count > 0 ? Math.round((publication.assessment_count / publication.access_count) * 100) : 0}%</td></tr>
                </table>
            </div>
        </div>
        
        <div class="row mt-3">
            <div class="col-12">
                <h6>公开链接</h6>
                <div class="input-group">
                    <input type="text" class="form-control" value="${window.location.origin}/public/scale/${publication.publication_token}" readonly>
                    <button class="btn btn-outline-secondary" onclick="copyToClipboard('${window.location.origin}/public/scale/${publication.publication_token}')">
                        <i class="bi bi-copy"></i> 复制
                    </button>
                </div>
            </div>
        </div>
    `;
    
    selectedPublicationId = publication.id;
}

// 管理发布状态
function managePublicationStatus(publicationId, scaleTitle, currentStatus) {
    document.getElementById('statusPublicationId').value = publicationId;
    document.getElementById('newStatus').value = currentStatus ? 'active' : 'inactive';
    document.getElementById('statusModalLabel').innerHTML = `
        <i class="bi bi-gear me-2"></i>管理发布状态 - ${scaleTitle}
    `;
    
    const modal = new bootstrap.Modal(document.getElementById('statusModal'));
    modal.show();
}

// 更新发布状态
function updatePublicationStatus() {
    const publicationId = document.getElementById('statusPublicationId').value;
    const newStatus = document.getElementById('newStatus').value;
    const reason = document.getElementById('statusReason').value;
    
    if (!newStatus) {
        showAlert('请选择新状态', 'warning');
        return;
    }
    
    apiRequest(`/api/admin/member-publications/${publicationId}/status`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
        },
        body: JSON.stringify({
            is_active: newStatus === 'active',
            reason: reason
        })
    })
    .then(response => {
        if (response.code === 200) {
            showAlert('状态更新成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('statusModal')).hide();
            loadPublications(currentPage);
            loadStatistics();
        } else {
            showAlert(response.message || '状态更新失败', 'error');
        }
    })
    .catch(error => {
        console.error('更新状态失败:', error);
        showAlert('状态更新失败', 'error');
    });
}

// 复制发布链接
function copyPublicationLink(publicationId) {
    // 这里需要先获取发布详情来获取token
    apiRequest(`/api/admin/member-publications/${publicationId}`, {
        method: 'GET',
        headers: {
            'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
        }
    })
    .then(response => {
        if (response.code === 200) {
            const link = `${window.location.origin}/public/scale/${response.data.publication_token}`;
            copyToClipboard(link);
            showAlert('链接已复制到剪贴板', 'success');
        }
    })
    .catch(error => {
        console.error('获取发布链接失败:', error);
        showAlert('获取发布链接失败', 'error');
    });
}

// 查看发布的测评记录
function viewPublicationAssessments(publicationId = null) {
    const id = publicationId || selectedPublicationId;
    if (id) {
        window.open(`/admin/member-publications/${id}/assessments`, '_blank');
    }
}

// 删除发布
function deletePublication(publicationId, scaleTitle) {
    if (confirm(`确定要删除发布"${scaleTitle}"吗？此操作不可撤销。`)) {
        apiRequest(`/api/admin/member-publications/${publicationId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
            }
        })
        .then(response => {
            if (response.code === 200) {
                showAlert('发布删除成功', 'success');
                loadPublications(currentPage);
                loadStatistics();
            } else {
                showAlert(response.message || '删除失败', 'error');
            }
        })
        .catch(error => {
            console.error('删除发布失败:', error);
            showAlert('删除发布失败', 'error');
        });
    }
}

// 导出发布数据
function exportPublications() {
    const params = new URLSearchParams({
        search: document.getElementById('searchInput')?.value || '',
        status: document.getElementById('statusFilter')?.value || '',
        scale_id: document.getElementById('scaleFilter')?.value || '',
        format: 'excel'
    });
    
    window.open(`/api/admin/member-publications/export?${params}`, '_blank');
}

// 刷新数据
function refreshData() {
    loadStatistics();
    loadPublications(currentPage);
    showAlert('数据已刷新', 'success');
}

// 复制到剪贴板
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        console.log('复制成功');
    }).catch(err => {
        console.error('复制失败:', err);
        // 降级方案
        const textArea = document.createElement('textarea');
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
    });
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 显示提示信息
function showAlert(message, type = 'info') {
    // 创建提示框
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type === 'error' ? 'danger' : type} alert-dismissible fade show position-fixed`;
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(alertDiv);
    
    // 3秒后自动消失
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.parentNode.removeChild(alertDiv);
        }
    }, 3000);
}

// API请求封装
function apiRequest(url, options = {}) {
    return fetch(url, {
        ...options,
        headers: {
            'Content-Type': 'application/json',
            ...options.headers
        }
    })
    .then(response => response.json())
    .catch(error => {
        console.error('API请求失败:', error);
        throw error;
    });
}

// 搜索框回车事件
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('searchInput');
    if (searchInput) {
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchPublications();
            }
        });
    }
});